import sys
from datetime import datetime
import argparse
import sys
import zipfile
import gzip

# import pytz

# from bson import CodecOptions
from bson import decode_file_iter

parser = argparse.ArgumentParser(description='mysql backup command line .',
                                 usage=None,
                                 add_help=True)
parser.add_argument('--get_oplog_time_interval', type=int, default=1,
                    help='拿oplog时间间隙(1:拿开始时间,2:拿结束时间;3.拿开始跟结束时间)', required=False)
parser.add_argument('--filename', '-f', type=str, help='oplog文件', required=False)
parser.add_argument('--start_time', type=str, help='oplog导入开始时间', required=False)
parser.add_argument('--stop_time', type=str, help='oplog导入结束时间', required=False)
# parser.add_argument('--command', '-c', type=str, help='command', required=False, nargs='?', const='')
args = parser.parse_args()
oplog_time_interval = args.get_oplog_time_interval
filename = args.filename


def format_ts(ts):
    # return ts
    ts_timestamp = ts.time
    dt_object = datetime.fromtimestamp(ts_timestamp)
    return dt_object.strftime('%Y-%m-%d %H:%M:%S %f')
    # return ts.as_datetime().strftime('%Y-%m-%dT%H:%M:%S')


def get_oplog_start_stop_time(file_name, get_oplog_time_interval):
    if "".endswith('.gz'):
        f = gzip.open(file_name, 'rb')
    # with open(file_name, 'rb') as f:
    else:
        # if file_name is None:
        #     file_name = sys.stdin.buffer.raw.read()
        f = open(file_name, 'rb')
    bson_data = decode_file_iter(f)
    print(bson_data)
    bson_get = next(bson_data)
    print(bson_get)
    start_ts = bson_get.get('ts')
    start_ts_return = format_ts(start_ts)
    if get_oplog_time_interval == 1:
        stop_ts_return = None
        # return start_ts_return, None
    else:
        for bson_document in bson_data:
            pass
        stop_ts = bson_document.get('ts')
        stop_ts_return = format_ts(stop_ts)
        if get_oplog_time_interval == 2:
            start_ts_return = None
            # return None, stop_ts_return
        elif get_oplog_time_interval == 3:
            return start_ts_return, stop_ts_return
    f.close()
    return start_ts_return, stop_ts_return


def main():
    start_time, stop_time = get_oplog_start_stop_time(filename, oplog_time_interval)
    print(start_time)
    print(stop_time)


if __name__ == "__main__":
    sys.exit(main())
